package com.jxb.demo.im.client;

import com.alibaba.fastjson.JSONObject;
import com.jxb.demo.im.MsgInfo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @desc 客户端处理器
 */
public class IMClientHandler extends SimpleChannelInboundHandler {

    private static Logger logger = LoggerFactory.getLogger(IMClientHandler.class);

    /**
     * @desc 客户端与服务端建立连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端连接服务端成功");
    }

    /**
     * @desc 客户端与服务端连接断开
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //客户端断链重连实现
        new IMClient().connect("127.0.0.1",8080);
    }

    /**
     * @desc 事件触发
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    /**
     * @desc 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * @desc channelRead 读取 channelRead0
     * @param channelHandlerContext
     * @param o
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        if(o instanceof MsgInfo){
            MsgInfo msgInfo = (MsgInfo) o;
            if(msgInfo != null && "heartBeat".equals(msgInfo.getMsgType())){
                logger.info("client send heartbeat:{}",JSONObject.toJSONString(msgInfo));
                MsgInfo respMsg = new MsgInfo();
                respMsg.setMsg("pong");
                respMsg.setFromId("client-0");
                respMsg.setToId("server-0");
                respMsg.setTimeStamp(System.currentTimeMillis());
                //发送心跳应答
                channelHandlerContext.writeAndFlush(respMsg);
            }else{

            }
        }
    }

}
